import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

const Home = () => import('@/views/Home/index.vue')
const Search = () => import('@/views/Search/index.vue')
const Detail = () => import('@/views/Detail')
const GoodsOrder = () => import("@/views/GoodsOrder/index.vue")
const Trade = () => import('@/views/Trade/index.vue')
const Login = () => import('@/views/login/index.vue')
const Register = () => import('@/views/register/index.vue')
const CartSuccess = () => import('@/views/AddCartSuccess')
const Pay = () => import("@/views/pay")
const PaySuccess = () => import("@/views/PaySuccess")
const Order = () => import('@/views/Order')
const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    name: "Home",
    path: "/home",
    component: Home,
  },
  {
    path: "/search",
    name: "Search",
    component: Search,
  },
  {
    path: '/detail/:id',
    name: "Detail",
    component: Detail,
  },
  {
    path: "/shopcart",
    component: GoodsOrder,
  },
  {
    name: "CartSuccess",
    path: "/cart_success",
    component: CartSuccess,
  },
  {
    path: "/trade",
    component: Trade,
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
    meta: {
      isHiddenHeader: true,
      isHiddenFooter: true,
    },
  },
  {
    path: "/register",
    name: "Register",
    component: Register,
    meta: {
      isHiddenHeader: true,
      isHiddenFooter: true,
    },
  },
  {
    path: "/pay",
    name: "Pay",
    component: Pay,
    meta: {
      isHiddenHeader: true,
      isHiddenFooter: true,
    },
  },
  {
    path: "/paysuccess",
    component: PaySuccess,
  },
  {
    path: "/order",
    name: 'Order',
    component: Order,
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    };
  },
});

// 路由导航守卫
const needLoginPath = ['/trade', '/shopcart', '/pay', '/order', '/paysuccess']
router.beforeEach((to, from, next) => {
  const user = localStorage.getItem('user')
  if (!user && needLoginPath.includes(to.path)) {
    next(`/login?redirect=${to.path}`)
    Vue.prototype.$message.error('请先登录')
  } else {
    next()
  }

})

export default router;
